<?php
/**
 * Created by PhpStorm.
 * User: youqingsong
 * Date: 2022/02/11
 * Time: 15:08
 */

namespace Ktnw\WechatSupport\Utils;


use Exception;

class HttpClient
{
    /**
     * [http 调用接口函数]
     * @Date   2020-07-14
     * @Author GeorgeHao
     * @param string $url [接口地址]
     * @param array $params [数组]
     * @param string $method [GET\POST\DELETE\PUT]
     * @param array $header [HTTP头信息]
     * @param integer $timeout [超时时间]
     * @return array [type]                [接口返回数据]
     * @throws Exception
     */
    public static function sendHttp(string $url, array $params = [], string $method = 'GET', array $header = [], int $timeout = 10): array
    {
        $headers = [
            $method == "GET" ? "Content-Type: application/json;charset=utf-8" : "Content-Type: application/x-www-form-urlencoded; charset=utf-8",
        ];
        if (!empty($headers)) {
            $header = array_merge($headers, $header);
        }

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        if (strtoupper(substr($url, 0, 5)) == 'HTTPS') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $params = empty($params) ? [] : $params;
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                if (strpos($url, "?") === false) {
                    $url .= '?&' . $params;
                } else {
                    $url .= '&' . $params;
                }
                curl_setopt($ch, CURLOPT_URL, $url);
                break;
            case 'POST':
                $params = empty($params) ? [] : $params;
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
                break;
            case 'DELETE':
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-HTTP-Method-Override: DELETE"]);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                break;
            case 'PUT':
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 0);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        $data = curl_exec($ch);
        //关闭URL请求
        curl_close($ch);
        return empty($data) ? [] : json_decode($data, true);
    }

}